#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import os
import sys
import shutil

execfile(os.path.join(sys.path[0], "framework.py"))

from unittest import TestCase, TestLoader, TextTestRunner
from oriolus.trotter.core import FetchError
from oriolus.trotter.fetchers.localfetcher import LocalFetcher

logging.basicConfig(level = logging.ERROR, format = "[%(levelname)s] %(message)s", )

class TestLocalFetcher(TestCase):
    cache = os.path.abspath("./testdata/cache")
    
    def setUp(self):
        if not os.path.exists(self.cache):
            os.makedirs(self.cache)
    
    def tearDown(self):
        if os.path.exists(self.cache):
            shutil.rmtree(self.cache)
            
        LocalFetcher.Folder_from_install = ""
    
    def test_set_path_for_fetcher(self):
        path = "D:\local_path"
        
        self.assertEqual("", LocalFetcher.Folder_from_install)
        fetcher = self.__get_local_fetcher(path)
        
        self.assertEqual(path, fetcher.Folder_from_install)
        self.assertEqual(path, LocalFetcher.Folder_from_install)
        self.assertEqual(path, LocalFetcher(None).Folder_from_install)
        
    def test_get_file_from_folder(self):
        file_url = "ftp://dev.shtrih-m.ru/oriolus/test_packet.zip.ori"
        LocalFetcher.Folder_from_install = "./testdata/localfetcherdata"
        
        fetcher = LocalFetcher(self.cache)
        file_name_in_cache = fetcher.get(file_url)
        
        self.assertEqual("test_packet.zip.ori", file_name_in_cache)
        
        expected_file_name = os.path.abspath(os.path.join(self.cache, file_name_in_cache))
        self.assertTrue(os.path.exists(expected_file_name))
        
    def test_get_file_were_folder_not_exists(self):
        file_url = "ftp://dev.shtrih-m.ru/oriolus/test_packet.zip.ori"
        LocalFetcher.Folder_from_install = "./testdata/notexistsfolder"
        fetcher = LocalFetcher(self.cache)
        
        self.assertRaises(FetchError, fetcher.get, file_url)
        
    def __get_local_fetcher(self, path):
        LocalFetcher.Folder_from_install = path
        
        return LocalFetcher(None)
    
if __name__ == "__main__":
    suite = TestLoader().loadTestsFromTestCase(TestLocalFetcher)
    TextTestRunner(verbosity=2).run(suite)   
    
